<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\Demands;
use app\api\model\v1\ProgramRecommendation;
use app\api\validate\v1\MediaValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Env;
use think\Request;

class Media extends BaseController
{
    use SearchDataForModel, FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 9:14
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取列表
     */
    public function getDemandList()
    {
        $map = [];
        if ($this->request->has('title') && !empty($this->request->param('title'))) {
            $map[] = ['title', 'like', '%' . $this->request->param('title') . '%'];
        }
        if ($this->request->has('status') && !empty($this->request->param('status'))) {
            $map[] = ['status', '=', $this->request->param('status')];
        }
        if ($this->request->has('demand_type') && !empty($this->request->param('demand_type'))) {
            $map[] = ['demand_type', '=', $this->request->param('demand_type')];
        }
        $limit = $this->request->param('limit', 10);
        $res = Demands::where($map)->order('create_time', 'desc')->paginate($limit)->each(function ($item, $key) {
            $item['url_cover'] = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $item['cover'];
            return $item;
        });
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/8/27
     * @Time: 10:04
     * @return \think\response\Json
     * 获取媒体类别
     */
    public function getMediaType()
    {
        $res = Demands::$media_type;
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/27
     * @Time: 11:32
     * @return \think\response\Json
     * 删除指定文件
     */
    public function delFile()
    {
        $data = $this->request->param();
        $type = $this->request->param('type', 1);
        if(strstr($data['file'], 'https') !== false){
            $file_a = explode('storage',$data['file']);
            $file_s = (substr($file_a[1],1));
        }else{
            $file_s = $data['file'];
        }
        if ($type === 2) {
            $uid = $this->request->param('uid');
            $name = $this->request->param('name');
            $type = substr(strrchr($name, "."), 1);
            $file = app()->getRootPath() . 'public/storage/record/' . $uid . '.' . $type;
        } else {
            $file = app()->getRootPath() . 'public/storage/' . $file_s;
        }
        if(!empty($data['file'])){
            if (file_exists($file)) {
                unlink($file);
            }
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 9:10
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存媒体信息
     */
    public function saveMedia()
    {
        $id = $this->request->param('id', 0);
        $data = $this->request->param();

        try {
            $validator = $this->validate($data, MediaValidate::rules($id), MediaValidate::msg());
            if ($validator) {
                $data['create_id'] = $this->request->uid; //用户id

                if (empty($this->request->param('cover'))) {
                    $data['cover'] = 'static/image/zanwu.jpg';
                }
                if (!empty($this->request->param('accessory_path'))) {
                    $data['accessory_path'] = json_encode($this->request->param('accessory_path'), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    $data['is_accessory'] = Demands::IS_ACCESSORY_ONE;
                }
                $data['demand_type'] = intval($data['demand_type']);
                $data['status'] = intval($data['status']);
                if (intval($id) === 0) {
                    Demands::create($data);
                } else {
                    $res = Demands::find($id);
                    if (is_null($res)) {
                        return $this->response(403, '数据不存在');
                    }
                    $res->save($data);
                }
                return $this->response();
            }
        } catch (ValidateException $exception) {
            return $this->response(403, $exception->getError());
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/27
     * @Time: 14:18
     * @return \think\response\Json
     * 上传录音
     */
    public function uploadRecord()
    {

        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $uid = $this->request->param('uid');
        $name = $this->request->param('name');
        $type = substr(strrchr($name, "."), 1);
        $result = $this->saveFileAs($file, 'record', $uid . '.' . $type);
        return $this->response($result);
    }


    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 9:36
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取唯一资源信息
     */
    public function getShowMedia($id)
    {
        $res = Demands::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }

        $file = app()->getRootPath() . 'public/storage/' . $res->cover;

        if (file_exists($file)) {
            $url = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $res->cover;
        } else {
            $url = Env::get('HTTP.http', 'HTTP.default_http') . $res->cover;
        }
        $data[] = ['name' => $res->title, 'url' => $url, 'file' => $res->cover];
        $res['img_fileList'] = $data;
        if ($res->demand_type === Demands::MEDIA_TYPE_TWO && $res->is_accessory === Demands::IS_ACCESSORY_ONE) {
            $res['rec_fileList'] = json_decode($res->accessory_path, true);
            $res['accessory_path'] = json_decode($res->accessory_path, true);
        }
        $res['demand_type'] = $res->demand_type . '';
        $res['status'] = $res->status . '';
        return $this->response($res->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/1
     * @Time: 14:44
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 微信端获取唯一媒体信息
     */
    public function getShowMediaInfo()
    {
        $id = $this->request->param('id');
        $res = Demands::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $file = app()->getRootPath() . 'public/storage/' . $res->cover;
        if (file_exists($file)) {
            $url = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $res->cover;
        } else {
            $url = Env::get('HTTP.http', 'HTTP.default_http') . $res->cover;
        }
        $data[] = ['name' => $res->title, 'url' => $url, 'file' => $res->cover];
        $res['img_fileList'] = $data;
        if ($res->demand_type === Demands::MEDIA_TYPE_TWO && $res->is_accessory === Demands::IS_ACCESSORY_ONE) {
            $res['rec_fileList'] = json_decode($res->accessory_path, true);
            $res['accessory_path'] = json_decode($res->accessory_path, true);
            $new_data = [];
            foreach ($res['accessory_path'] as $key => $v) {
                $new_data[$key]['src'] = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $v['url'];
                $new_data[$key]['poster'] = $url;
                $new_data[$key]['name'] = $res['title'] . '-' . ($key+1);
                $new_data[$key]['author'] = $res['create_id'];

            }
            $res['audioMp3'] = $new_data;
        }
        return $this->response($res->toArray());
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 10:40
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除 对应的文件
     */
    public function deleteMedia($id)
    {
        $res = Demands::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }

        if ($res->demand_type === Demands::MEDIA_TYPE_TWO || $res->is_accessory === Demands::IS_ACCESSORY_ONE) {
            if (!empty($res->accessory_path)){
                $rec_fileList = json_decode($res->accessory_path, true);
                foreach ($rec_fileList as $key => $value) {
                    $file = app()->getRootPath() . 'public/storage/' . $value['url'];
                    if (file_exists($file)) {
                        unlink($file);
                    }
                }
            }

        }
        if (!empty($res->cover)) {
            $file = app()->getRootPath() . 'public/storage/' . $res->cover;
            if (file_exists($file)) {
                unlink($file);
            }
        }
        $res->force()->delete();
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/7
     * @Time: 19:15
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存节目推荐
     */
    public function saveProgramRecommendation(){
        $id = $this->request->param('id',0);
        $data = $this->request->param();
        $data['create_id'] = $this->request->uid; //用户id
        if (empty($this->request->param('cover'))) {
            $data['cover'] = 'static/image/zanwu.jpg';
        }
        $data['status'] = intval($data['status']);
        if (intval($id) === 0) {
            ProgramRecommendation::create($data);
        } else {
            $res = ProgramRecommendation::find($id);
            if (is_null($res)) {
                return $this->response(403, '数据不存在');
            }
            $res->save($data);
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/7
     * @Time: 19:17
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 节目列表
     */
    public function getProgramRecommendation(){
        $map = [];
        if ($this->request->has('title') && !empty($this->request->param('title'))) {
            $map[] = ['title', 'like', '%' . $this->request->param('title') . '%'];
        }
        if ($this->request->has('status') && !empty($this->request->param('status'))) {
            $map[] = ['status', '=', $this->request->param('status')];
        }
        $limit = $this->request->param('limit', 10);
        $res = ProgramRecommendation::where($map)->order('create_time', 'desc')->paginate($limit)->each(function ($item, $key) {
            $item['url_cover'] = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $item['cover'];
            return $item;
        });
        return $this->response($res);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/7
     * @Time: 19:30
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除
     */
    public function delProgramRecommendation($id){
        $res = ProgramRecommendation::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        if (!empty($res->cover)) {
            $file = app()->getRootPath() . 'public/storage/' . $res->cover;
            if (file_exists($file)) {
                unlink($file);
            }
        }
        $res->force()->delete();
        return $this->response();
    }
}
